package com.knshare.gen.service.impl;

import com.knshare.gen.config.DBConfig;
import com.knshare.gen.config.GenConfig;
import com.knshare.gen.dao.GenTableDao;
import com.knshare.gen.domain.GenTableColumn;
import com.knshare.gen.service.IGenTableEntityService;
import com.knshare.utils.StringUtils;
import com.knshare.utils.VelocityUtils;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;

import java.io.FileWriter;
import java.io.IOException;
import java.util.List;
import java.util.Properties;

/**
 * 实体类生成Service
 *
 * @author 杨静 1475654312@qq.com
 */
public class GenTableEntityServiceImpl implements IGenTableEntityService {

    /**
     * 生成实体类
     *
     * @param genConfig 代码生成配置
     * @param dbConfig 数据库配置
     */
    @Override
    public void genTableEntity(GenConfig genConfig, DBConfig dbConfig) {
        // 设置velocity资源加载器
        Properties prop = new Properties();
        prop.put("file.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
        Velocity.init(prop);
        // 设置参数
        List<GenTableColumn> genTableColumns = GenTableDao.selectGenTableByName(dbConfig, genConfig.getTableName());
        Template template = VelocityUtils.getTemplate("vm/domain.vm" , "UTF-8");
        VelocityContext velocityContext = new VelocityContext();
        velocityContext.put("packageName",genConfig.getPackageName());
        velocityContext.put("tableName",genConfig.getTableName());
        velocityContext.put("author",genConfig.getAuthor());
        velocityContext.put("email",genConfig.getEmail());
        velocityContext.put("ClassName", StringUtils.parseGreatHump(genConfig.getTableName()));
        velocityContext.put("columns",genTableColumns);
        // 渲染模板
        FileWriter fw;
        try {
            fw = new FileWriter(genConfig.getGenPath());
            template.merge(velocityContext, fw);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        //释放资源
        try {
            fw.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
